import 'package:erp/res/resources.dart';
import 'package:erp/widgets/form1/form_builder.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class ClearableTextFormField extends BaseFormField {
  final String name;
  final String placeholder;
  final String? label;
  final String? Function(dynamic value)? validator;
  final TextInputType? keyboardType;
  final List<TextInputFormatter>? inputFormatters;

  ClearableTextFormField({
    required this.name,
    this.inputFormatters,
    this.label,
    this.validator,
    this.placeholder = '请输入',
    this.keyboardType = TextInputType.text,
  }) : super(name: name, label: label, validator: validator);

  @override
  _ClearableTextFormFieldState createState() {
    return _ClearableTextFormFieldState();
  }
}

class _ClearableTextFormFieldState extends BaseFormFieldState {
  late final TextEditingController _controller;

  dynamic get initialValue {
    if (initValueMap != null && initValueMap!.containsKey(name)) {
      return initValueMap![name] ?? "";
    }
    return "";
  }

  ClearableTextFormField get _widget => (widget as ClearableTextFormField);

  @override
  Widget build(BuildContext context) {
    bool _readOnly = false;
    if (initStateMap != null && initStateMap!.containsKey('readOnly')) {
      _readOnly = initStateMap!['readOnly']!;
    }

    var valueTextColor = Colours.FORM_FIELD_VALUE_COLOR;
    var hintText = '';
    if (!_readOnly) {
      hintText = (widget as ClearableTextFormField).placeholder;
      valueTextColor = Colours.FORM_FIELD_LABEL_COLOR;
    }

    return labelWrapper(
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Expanded(
            child: TextField(
              key: key,
              keyboardType: _widget.keyboardType,
              readOnly: _readOnly,
              controller: _controller,
              textAlign: TextAlign.right,
              style: Styles.genNormalTextStyle(color: valueTextColor),
              inputFormatters: _widget.inputFormatters,
              decoration: InputDecoration(
                hintText: hintText,
                hintStyle: Styles.genNormalTextStyle(color: Colours.PLACE_HOLDER_COLOR),
                contentPadding: EdgeInsets.only(bottom: 2),
                border: InputBorder.none,
                enabledBorder: InputBorder.none,
                focusedBorder: InputBorder.none,
                disabledBorder: InputBorder.none,
                errorBorder: InputBorder.none,
                focusedErrorBorder: InputBorder.none,
              ),
            ),
          ),
          !_readOnly
              ? GestureDetector(
                  child: Offstage(
                    offstage: _controller.text.length == 0,
                    child: Container(
                      padding: EdgeInsets.only(top: 1),
                      alignment: AlignmentDirectional.center,
                      child: Image.asset(
                        'assets/images/clear.png',
                        width: 28.w,
                        height: 28.w,
                      ),
                    ),
                  ),
                  onTap: () {
                    setState(() {
                      _controller.text = '';
                      value = '';
                    });
                  },
                )
              : SizedBox.shrink(),
        ],
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    value = '';
    _controller = TextEditingController();
    _controller.addListener(() {
      setState(() {
        value = _controller.text;
      });
    });
  }

  void initFormManagement() {
    super.initFormManagement();
    _controller.text = initialValue.toString();
    value = initialValue.toString();
  }

  void dispose() {
    super.dispose();
    _controller.dispose();
  }
}

///

class ClearableTextareaFormField extends BaseFormField {
  final String name;
  final String placeholder;
  final String? label;
  final String? Function(dynamic value)? validator;
  final TextInputType? keyboardType;

  ClearableTextareaFormField({
    required this.name,
    this.label,
    this.validator,
    this.placeholder = '请输入',
    this.keyboardType = TextInputType.text,
  }) : super(name: name, label: label, validator: validator, labelPosition: LabelPosition.top);

  @override
  BaseFormFieldState createState() {
    return _ClearableTextareaFormField();
  }
}

class _ClearableTextareaFormField extends BaseFormFieldState {
  late final TextEditingController _controller;

  dynamic get initialValue {
    if (initValueMap != null && initValueMap!.containsKey(name)) {
      return initValueMap![name] ?? "";
    }
    return "";
  }

  @override
  Widget build(BuildContext context) {
    bool _readOnly = false;
    if (initStateMap != null && initStateMap!.containsKey('readOnly')) {
      _readOnly = initStateMap!['readOnly']!;
    }

    var valueTextColor = Colours.FORM_FIELD_VALUE_COLOR;
    var hintText = '';
    if (!_readOnly) {
      hintText = (widget as ClearableTextareaFormField).placeholder;
      valueTextColor = Colours.FORM_FIELD_LABEL_COLOR;
    }

    var _widget;
    _widget = TextField(
      readOnly: _readOnly,
      key: key,
      minLines: 3,
      maxLines: 3,
      maxLength: 200,
      controller: _controller,
      textAlign: TextAlign.left,
      style: Styles.genNormalTextStyle(color: valueTextColor),
      decoration: InputDecoration(
        contentPadding: EdgeInsets.all(0),
        counterText: '${_controller.text.length}/200',
        border: InputBorder.none,
        enabledBorder: InputBorder.none,
        focusedBorder: InputBorder.none,
        disabledBorder: InputBorder.none,
        errorBorder: InputBorder.none,
        focusedErrorBorder: InputBorder.none,
        hintText: hintText,
        hintStyle: Styles.genNormalTextStyle(color: Colours.PLACE_HOLDER_COLOR),
      ),
    );
    if (!_readOnly) {
      _widget = Row(
        children: [
          Expanded(
            child: _widget,
          ),
          GestureDetector(
            child: Offstage(
              offstage: _controller.text.length == 0,
              child: Center(
                child: Image.asset(
                  'assets/images/clear.png',
                  width: 28.w,
                  height: 28.w,
                ),
              ),
            ),
            onTap: () {
              _controller.text = '';
              // if (model != null && (prop.isNotEmpty)) {
              //   model[prop] = '';
              // }
              setState(() {});
            },
          ),
        ],
      );
    }
    return labelWrapper(
      child: Container(
        padding: EdgeInsets.fromLTRB(20.w, 14.h, 20.w, 14.h),
        decoration: BoxDecoration(
          border: Border.all(
            color: Color(0xFFE6E6E6),
            width: 1.w,
          ),
          color: Color(0xFFFAFAFA),
        ),
        child: _widget,
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    value = '';
    _controller = TextEditingController();
    _controller.addListener(() {
      setState(() {
        value = _controller.text;
      });
    });
  }

  void initFormManagement() {
    super.initFormManagement();
    _controller.text = initialValue.toString();
    value = initialValue.toString();
  }

  void dispose() {
    super.dispose();
    _controller.dispose();
  }
}
